package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.constants.SettingAdPositionEnum;
import cn.com.chengmandian.bike.mapper.EbSettingAdMapper;
import cn.com.chengmandian.bike.model.EbSettingAd;
import cn.com.chengmandian.bike.service.IEbSettingAdService;
import cn.com.chengmandian.bike.utils.CaffeineUtils;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 电单车运营-广告配置 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2022-02-09
 */
@Slf4j
@Service
public class EbSettingAdServiceImpl extends ServiceImpl<EbSettingAdMapper, EbSettingAd> implements IEbSettingAdService {

    /**
     * 获取广告列表
     */
    @Override
    public List<EbSettingAd> getList(Integer agentId, Integer areaId, Integer position) {
        String key = agentId + "_" + areaId + "_" + (position == null ? 0 : position);
        List<EbSettingAd> list = CaffeineUtils.getAdList(key);
        if(list != null) return list;
        return getDbList(agentId, areaId, position);
    }

    /**
     * 数据库获取缓存
     * @return
     */
    private List<EbSettingAd> getDbList(Integer agentId, Integer areaId, Integer position) {
        String key = agentId + "_" + areaId + "_" + (position == null? 0 : position);
        List<EbSettingAd> list = this.list(new LambdaQueryWrapper<EbSettingAd>()
                .eq(EbSettingAd::getAreaId, areaId)
                .eq(EbSettingAd::getIsEnabled, CommonConstant.ONE)
                .eq(EbSettingAd::getIsDeleted,CommonConstant.ZERO)
                .eq(ObjectUtil.isNotNull(position),EbSettingAd::getPosition,position)
                .orderByAsc(EbSettingAd::getSort));
        CaffeineUtils.putAdList(key, list);
        return list;
    }

    /**
     * 刷新运营区全部广告位缓存
     * @param agentId
     * @param areaId
     */
    @Override
    public void loadCache(Integer agentId, Integer areaId) {
        for(SettingAdPositionEnum item : SettingAdPositionEnum.values()) {
            this.getDbList(agentId, areaId, item.getType());
        }
        this.getDbList(agentId, areaId, 0);
        log.info("本地广告缓存已加载：" + agentId + "," + areaId);
    }
}
